// swim project swim.go
package main

import (
	"fmt"
	"swim/etc"
	"swim/request/servicerequest"
	"swim/request/webrequest"
	//"swim/util/nuid"
	//	"io"
	"log"
	"net/http"
	"runtime"
	"swim/contain"
	"swim/redisclient"

	//"github.com/garyburd/redigo/redis"
)

func safeHandler(fn http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		defer func() {
			if e, ok := recover().(error); ok {
				http.Error(w, "Internal error", http.StatusInternalServerError)
				// 或者输出自定义的 50x 错误页面
				// w.WriteHeader(http.StatusInternalServerError)
				// renderHtml(w, "error", e)

				// logging
				log.Println("WARN: panic in %v - %v", fn, e)
				//log.Println(string(debug.Stack()))
			}
		}()
		fn(w, r)
	}
}
func main() {

	runtime.GOMAXPROCS(runtime.NumCPU()) //开启最多处理器模式
	contain.NewContain()                 //加载容器
	contain.StartGC()                    //开启过时清理任务
	contain.StartPushOnlineUsers()       //定时更新在线用户
	redisclient.LoadCache()              //初始化缓存连接

	http.HandleFunc("/msg/", safeHandler(webrequest.ClientMsgLoop))       //消息端操作
	http.HandleFunc("/service/", safeHandler(servicerequest.OnService))   //服务端操作
	http.HandleFunc("/upload/", safeHandler(servicerequest.OnUploadFile)) //文件上传
	http.HandleFunc("/suser/", safeHandler(servicerequest.OnServiceUser)) //服务用户信息
	http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static"))))
	http.Handle("/down/", http.StripPrefix("/down/", http.FileServer(http.Dir(etc.SwImConfiger.UploadFilePath))))

	http.Handle("/", http.RedirectHandler("/static/html/index.html", http.StatusFound))
	/*
		http.HandleFunc("/config.js", func(w http.ResponseWriter, r *http.Request) {
			var js_debug string = "false"
			if etc.Debug {
				js_debug = "true"
			}
			io.WriteString(w, fmt.Sprintf("var config = {host:'%s', port: %s, debug: %s};\n", etc.ServerHost, etc.ServerPort, js_debug))
		})
	*/
	var svr_ = fmt.Sprintf("%s:%d", etc.SwImConfiger.ServerHost, etc.SwImConfiger.ServerPort)
	log.Printf("Server start on %s\n", svr_)
	if err := http.ListenAndServe(svr_, nil); err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}
